Page({
  data: {
    baseURL:wx.baseURL,
    total:0,
    rows:[],
    brandSlected:{},//已选品牌
    brands:[],
    brandVisible:false,
    query:{
      key:'',//搜索关键字
      brandIds:'',
      sorted:0,
      pageNum:1,
      pageSize:10
    },
  },

  //清空选择的品牌
  clearBrand(){
    this.setData({
      brandSlected:{}
    })
  },

  //按品牌进行搜索
  confimBrand(){
    let brandIds = []
    for(let key in this.data.brandSlected){//取出选择的品牌id
      if(key && this.data.brandSlected[key]) brandIds.push(key)
    }
    this.data.query.brandIds = brandIds.join(',')
    this.refresh(() => {
      this.setData({
        brandVisible:false
      })
    })
  },

  //切换品牌选中状态
  changeBrand(e){
    let brandSlected = this.data.brandSlected
    let id = e.currentTarget.dataset.id
    brandSlected[id] = !brandSlected[id] //取反 切换选中状态
    this.setData({
      brandSlected
    })
  },

  back:function(){
    wx.switchTab({
      url: '/pages/fl/fl',
    })
  },

  // 切换品牌弹窗
  changeShowBrands(){
    let brandSlected = {}
    if(!this.data.brandVisible && this.data.query.brandIds){ // 打开品牌弹框
      // 按上一次选择结果初始化已选中品牌
      let brandIds = this.data.query.brandIds.split(',')
      for(let i = 0; i < brandIds.length ; i++){
        brandSlected[brandIds[i]] = true
      }
    }
    this.setData({
      brandVisible:!this.data.brandVisible,
      brandSlected
    })
  },

  //搜索关键字
  inputKey(e){
    this.data.query.key = e.detail.value
  },

  //修改排序方式
  changeSorted(e){
    let sorted = e.currentTarget.dataset.sorted
    this.setData({
      'query.sorted' : sorted
    })
    //刷新
    this.refresh()
  },
  detail:function (e) {
    wx.navigateTo({
      url: '/pages/details/details',
    })
  },

  //重新加载
  refresh(next) {
    this.data.query.pageNum == 1
    this.data.rows = []
    this.data.total = 0 
    this.getList(next)
  },

  getList(next){
    wx.get('/products',this.data.query).then(res=>{
      console.log(res);
      res.rows.forEach((item,index) => {
        item.img = wx.baseURL + item.productImgs.split(',')[0]
      })
      this.setData({
        total:res.total,
        rows:this.data.rows.concat(res.rows)
      })
      if(typeof next == 'function') next()
    })
  },


  onPullDownRefresh: function (params) {
    this.refresh(() => {
      wx.stopPullDownRefresh()
    })
  },

  onReachBottom : function () {
      this.data.query.pageNum ++
      if(this.data.rows.length < this.data.total) this.getList()
  },

  return:function(e){
    wx.navigateBack({
      data:1
    })
  },

  //获取品牌列表
  getBrands(){
    wx.get('/brands').then(res => {
      this.setData({
        brands:res
      })
    })
  },

  onLoad: function (options) {
    this.setData({
      'query.key':options.key || '',
      'query.brandIds':options.brandIds || ''
    })
    this.getBrands()
    this.getList()
  },
})